package cn.logicalthing.demo.web.bean;

import com.core.bean.ShoppingCar;
import com.core.bean.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class WebShoppingCar extends ShoppingCar {

    public static final String SESSION_KEY_USER = "USER";
    public static final String SESSION_KEY_SHOP = "SHOP";
    public static final String SESSION_KEY_CAR = "CAR";

    @Override
    public void save(User user, String shopId) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_KEY_USER, user);
        session.setAttribute(SESSION_KEY_SHOP, shopId);
        session.setAttribute(SESSION_KEY_CAR, this);
    }

    public static WebShoppingCar getCar() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object car = request.getSession().getAttribute(SESSION_KEY_CAR);
        if (car == null) {
            return new WebShoppingCar();
        }
        return (WebShoppingCar) car;
    }
}
